<template>
  <view class="wrap" v-if="showPage">
    <view class="pox">
      <uv-navbar fixed title="动态" safeAreaInsetTop placeholder :border='false'>
        <template #left>
          <template v-if="userDetail">
            <avatar :src='setUrl(userDetail.avatar)' styles='width: 72rpx; height: 72rpx;border: 1px solid #FFF;margin-right: 30rpx' @click="goUser"></avatar>
          </template>
        </template>
        <template v-slot:right>
          <view class="order">
            <view class="item" @click="goMsg">
              <image src="../../static/ling.png" class="img"></image>
              <uv-badge :isDot="true" bgColor='#E43222' absolute :offset="[0, 0]" :show='showBadge'></uv-badge>
            </view>
            <view class="item" @click="goTag">
              <image src="../../static/sou.png" class="img"></image>
            </view>
          </view>
        </template>
      </uv-navbar>
    </view>
    <view class="search" :style="'top: ' + statusBar">
      <view class="input">
        <view class="test">
          <uv-input v-model="test" placeholder="大家都在搜：新能源" border="none" placeholderStyle='font-weight: 400; font-size: 24rpx; color: #B8B8B8;' fontSize='24rpx' color='#2B2B2B' :customStyle="{height: '100%'}" confirmType='search' @confirm='search'></uv-input>
        </view>
        <view class="icon" @click="search"><image src="../../static/searchIcon.png" class="img"></image></view>
      </view>
    </view>
    <view class="banner" v-if="swiperList.length">
      <view class="swiper">
        <uv-swiper :list="swiperList" keyName='image' bgColor='rgba(0,0,0,0)' :indicator='swiperList.length > 1' indicatorMode='dot' indicatorStyle='bottom: 20rpx' indicatorInactiveColor='#FFFFFF' @click='swiperChange'></uv-swiper>
      </view>
    </view>
    <uv-gap height="16rpx" bgColor="#F5F5F5"></uv-gap>
    <view class="dyTab">
      <template v-for="(item, index) in tabsList" :key="index">
        <view class="item" :class="{ active: active == item.id }" @click="tabsClick(item)">{{ item.name }} <uv-icon name="arrow-down" v-if="index <= 1"></uv-icon> <text class="hine" v-if="active == item.id"></text></view>
      </template>
    </view>
    <view class="tops" v-if="topList.length && active != 4">
      <view class="item" v-for="(item, index) in topList" :key="index" @click="goDetail(item)">
        <text class="set">置顶</text>{{ item.title }}
      </view>
    </view>
    <view class="theme">
      <template v-for="(item, index) in list" :key="index">
        <view class="addImage" v-if="item.myType && item.myType == 'image'" @click="goSwiperDetial(item)">
          <image :src="setUrl(item.image)" mode="widthFix" class="img"></image>
        </view>
        <news :detail='item' @followClick='followClick' v-else></news>
      </template>
    </view>
    <uv-empty :show='showLeng' mode="list" marginTop='200rpx'></uv-empty>
    <topPopup ref="popup" @click="tap"></topPopup>
    <view class="fab">
      <uni-fab direction='vertical' horizontal='right' vertical='bottom' :pattern="pattern" :content="content" @trigger='trigger'></uni-fab>
    </view>
    
    <tabbar :current='1'></tabbar>
  </view>
</template>

<script setup>
import news from '../../components/dynamic/news.vue';
import topPopup from '../../components/dynamic/topPopup.vue';
import { ref, computed, onMounted } from 'vue';
import { useUser } from '@/store';
import { setUrl, toast, getBanner, deepArr } from '@/common';
import { post } from '@/api';
import { onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app';
import { sys } from '@/uni_modules/uv-ui-tools/libs/function/index.js';

const popup = ref(null);
const userDetail = computed(() => {
  const store = useUser();
  return store.userDetail;
});
const tabsList = [{ name: '广场', id: 0 }, { name: '关注', id: 4 }, { name: '官方发布', id: 1 }, { name: '研报', id: 2 }];
const pattern = { color: '#000', selectedColor: '#000', buttonColor: '#E43222' };
const content = [
  { iconPath: '/static/image.png', selectedIconPath: '/static/image.png', text: '发图文', active: false }, 
  { iconPath: '/static/file.png', selectedIconPath: '/static/file.png', text: '发文件', active: false }
];
const statusBar = sys().statusBarHeight + 44 + 'px'
let swiperList = ref([]);
let plaque = ref([]);
let active = ref(0);
let test = ref('');
let topList = ref([]);
let list = ref([]);
let last_page = 0;
let page = 1;
let limit = 15;
let listIndex = 9; // 跟踪插入的广告图位置
let adIndex = 0;
let showLeng = ref(false);
let showPage = ref(false);
let showBadge = ref(false);
let opt = ref({
  type: 0,
  tag_id: ''
});

onMounted(() => {
  const tag = uni.getStorageSync('tag');
  if(!userDetail.value.tag_ids && !tag){
    uni.setStorageSync('tag', true);
    uni.navigateTo({
      url: '/pages/dynamic/tag'
    });
  }
  // 获取顶部轮播图
  getBanner({ page: 1, limit: 100, position: 5 }).then(res => {
    swiperList.value = res;
  })
})
// 下拉刷新
onPullDownRefresh(() => {
  page = 1
  list.value = [];
  getList();
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 1000)
})
// 上拉加载
onReachBottom(async () => {
  if(last_page < page || last_page == page) return;
  page++
  await getList();
  uni.hideLoading();
})
onShow(() => {
  page = 1
  listIndex = 9;
  adIndex = 0;
  setTimeout(() => {
    list.value = [];
    getInsert();
    getMessage();
  }, 100)
})

function getInsert(){
  getBanner({ page: 1, limit: 100, position: 1 }).then(res => {
    plaque.value = res.map(e => {
      return{
        ...e,
        myType: 'image'
      }
    });
    getTopToList();
    getList();
  })
}
function getList(){
  const params = {
    page,
    limit,
    ...opt.value
  }
  if(active.value == 4){
    params.my_follow = 1;
  }else{
    params.display = active.value;
  }
  post('api/news/getNewsList', params).then(res => {
    if(res.code == 1){
      const data = res.data;
      last_page = data.last_page;
      if(plaque.value.length){ //如果有插屏广告图，就特殊处理
        const adsToList = insertAdsInList(data.data);
      }else{ // 没有的话，就按以前的处理
        list.value = [...list.value, ...data.data];
      }
      
      if(list.value.length){
        showLeng.value = false;
      }else{
        showLeng.value = true;
      }
      showPage.value = true;
    }
  })
}
// 处理函数：在列表中每隔10条数据插入广告
function insertAdsInList(data) {
  let arr = deepArr(list.value);
  let result = [];
  data.forEach((e, index) => {
    result.push(e);
    if(index == listIndex){
      if(plaque.value[adIndex]){
        result.push(plaque.value[adIndex]);
        adIndex += 1;
      }else{
        adIndex = 0;
        result.push(plaque.value[adIndex]);
      }
    }
    if(index == 14){
      listIndex = listIndex == 9 ? 4 : 9;
    }
  })
  list.value = [...list.value, ...result];
}
function getTopToList() {
  const params = {
    page: 1,
    limit: 3,
    is_top: 1,
    ...opt.value
  }
  if(active.value == 4){
    params.my_follow = 1;
  }else{
    params.display = active.value;
  }
  post('api/news/getNewsList', params).then(res => {
    if(res.code == 1){
      const data = res.data;
      topList.value = data.data;
    }
  })
}
function getMessage(){
  post('api/message/homeMessage').then(res => {
    const data = res.data;
    let sum = 0;
    for(let key in data){
      if(typeof data[key] == 'number'){
        sum += data[key]
      }
    }
    showBadge.value = sum > 0 ? true : false;
  })
}
function tap(row){
  opt.value = uni.$uv.deepClone(row);
  getTopToList()
  page = 1
  list.value = [];
  getList();
}
function followClick(row){
  list.value.forEach(e => {
    if(row.userId == e.user.id){
      e[row.type] = e[row.type] == 1 ? 0 : 1;
    }
  })
}
function search(){
  list.value = [];
  page = 1;
  getList();
}
function tabsClick(row){
  if(row.id == 0 || row.id == 4){
    if(active.value == row.id){
      popup.value.init(opt.value);
      popup.value.open();
      return;
    }
  }
  opt.value = {
    type: 0,
    tag_id: ''
  }
  active.value = row.id;
  list.value = [];
  page = 1;
  if(active.value != 4) getTopToList();
  getList();
}
function goDetail(row){
  let url = row.type != 3 ? '/pages/dynamic/detail' : '/pages/dynamic/videoDetail'
  uni.navigateTo({
    url: `${url}?id=${row.id}`
  });
}
function goSwiperDetial(row){
  const type = row.jump_type;
  if(type == 1) return;
  if(type == 3){
    uni.navigateTo({
      url: row.jump_url
    });
    return;
  }
  if(type == 2){
    uni.setStorageSync('WEBURL', row.jump_url);
  }
}
function swiperChange(index){
  const obj = swiperList.value[index];
  if(obj){
    const type = obj.jump_type;
    if(type == 1) return;
    if(type == 3){
      uni.navigateTo({
        url: obj.jump_url
      });
      return;
    }
    if(type == 2){
      uni.setStorageSync('WEBURL', obj.jump_url);
      uni.navigateTo({
        url: '/pages/view'
      });
    }
  }
}
function goUser(){
  uni.navigateTo({
  	url: '/pages/mine/index'
  });
}
function goMsg(){
  uni.navigateTo({
    url: '/pages/mine/message/index'
  });
}
function goTag(){
  uni.navigateTo({
    url: '/pages/dynamic/tag'
  });
}
function trigger({ index }){
  let url = index == 0 ? '/pages/dynamic/issue-image' : '/pages/dynamic/issue-file';
  uni.navigateTo({
    url
  });
}
</script>

<style lang="scss" scoped>
  .fab{
    :deep(.uni-fab--rightBottom){
      bottom: 300rpx;
    }
    :deep(.uni-fab__circle--rightBottom){
      bottom: 300rpx;
    }
    :deep(.uni-fab__content--other-platform){
      box-shadow: 0 1px 5px 2px rgba(0, 0, 0, 0.1)
    }
  }
  .tops{
    padding: 0 30rpx;
    padding-bottom: 40rpx;
    .item{
      overflow:hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      font-weight: 400;
      font-size: 28rpx;
      color: #737373;
      margin-top: 24rpx;
      .set{
        height: 32rpx;
        line-height: 32rpx;
        border: 1rpx solid #E43222;
        border-radius: 32rpx;
        font-weight: 400;
        font-size: 20rpx;
        color: #E43222;
        padding: 0 12rpx;
        text-align: center;
        margin-right: 10rpx;
      }
    }
  }
  .dyTab{
    width: 100%;
    height: 90rpx;
    margin-bottom: 40rpx;
    display: flex;
    align-items: center;
    .item{
      flex: 1;
      font-weight: 500;
      font-size: 28rpx;
      color: #999999;
      height: 90rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      position: relative;
      &.active{
        font-size: 36rpx;
        color: #2B2B2B;
      }
      .hine{
        width: 36rpx;
        height: 6rpx;
        background: #E43222;
        border-radius: 3rpx;
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
      }
    }
  }
  .theme{
    padding: 0 30rpx;
  }
  .banner{
    padding: 0 30rpx;
    padding-bottom: 30rpx;
    .swiper{
      border-radius: 24rpx;
      overflow: hidden;
    }
  }
  .order{
    width: 112rpx;
    display: flex;
    align-items: center;
    .item{
      width: 40rpx;
      height: 40rpx;
      position: relative;
      &:last-child{
        margin-left: 32rpx;
      }
    }
  }
  .search{
    padding: 0 30rpx;
    padding-top: 16rpx;
    padding-bottom: 20rpx;
    position: sticky;
    left: 0;
    top: 44px;
    background-color: #FFFFFF;
    z-index: 1001;
    .input{
      height: 72rpx;
      border-radius: 72rpx;
      border: 2rpx solid #2B2B2B;
      display: flex;
      align-items: center;
      .test{
        flex: 1;
        padding: 0 20rpx;
      }
      .icon{
        width: 80rpx;
        height: 56rpx;
        margin-right: 8rpx;
      }
    }
  }
  .pox{
    position: relative;
    background-color: #fff;
    width: 100%;
    z-index: 1001;
  }
</style>